<?
class cms extends model{
	public $gravy;
	public $url="";
	public $view="default";
	public $controller="default";
	public $title=NULL;
	public $description=NULL;
	public $keywords=NULL;
	public $content=NULL;
	public $meta=NULL;
	const NEST_REPEATER="!nest!";

	function __construct(){
		parent::__construct("cms");
	}

	public function getNestedItems($where=NULL,$orderBy=NULL,$limit=NULL){
		$sQl="
			SELECT
				node.id,
				node.user_id,
				node.title,
				CONCAT(REPEAT('".cms::NEST_REPEATER."',(COUNT(parent.title)-1)),node.title) nestedTitle,
				u.firstName,
				u.lastName,
				node.url,
				node.theme,
				node.controller,
				node.title,
				node.description,
				node.keywords,
				node.content,
				node.product_id,
				node.meta,
				node.published,
				node.status,
				node.dateAdded,
				node.dateUpdated,
				IF(node.rgt-node.lft>1,1,0) hasChildren
			FROM
				cms AS node,
				cms AS parent,
				user u
			WHERE
				node.status=1
				AND parent.status=1
				AND node.lft BETWEEN parent.lft AND parent.rgt
				AND u.status=1
				AND u.id=node.user_id
			GROUP BY
				node.id,
				node.user_id,
				node.title,
				u.firstName,
				u.lastName,
				node.url,
				node.theme,
				node.controller,
				node.title,
				node.description,
				node.keywords,
				node.content,
				node.product_id,
				node.meta,
				node.published,
				node.status,
				node.dateAdded,
				node.dateUpdated
			ORDER BY
				node.lft;
		";
		return($this->getRowsQuery($sQl,$where,$sortOrder,$limit));
	}

	public function getItems($where=NULL,$orderBy=NULL,$limit=NULL){
		$result=false;
		$where=($where===NULL)?"":"AND $where";
		$specialSort=($orderBy===NULL);
		$orderBy=($orderBy===NULL)?"parent_id,id":$orderBy;
		$limit=($limit===NULL)?"":"LIMIT ".$limit;

		$this->dbConnect();
		/* Get the  */
		$sQl="
			SELECT
				c.id,
				c.user_id,
				c.parent_id,
				u.firstName,
				u.lastName,
				c.url,
				c.theme,
				c.controller,
				c.title,
				c.description,
				c.keywords,
				c.content,
				c.product_id,
				c.meta,
				c.published,
				c.status,
				c.dateAdded,
				c.dateUpdated
			FROM
				cms c
				LEFT JOIN user u ON c.user_id=u.id
			WHERE
				c.status=1
				$where
			ORDER BY
				$orderBy
		";
		if($this->db->exec($sQl,true)){
			$result=$this->db->rows;
			$tmp1=$this->db->rows;
			if($specialSort){
				$tmp=array();
				$c=0;
				while(count($tmp1)>0){
					$tmp[]=$tmp1[0];
					$id=$tmp1[0]["id"];
					for($i=0;$i<count($tmp1);$i++){
						if($tmp1[$i]["parent_id"]==$id){
							$tmp[]=$tmp1[$i];
							array_splice($tmp1,$i,1);
							$i--;
						}
					}
					array_splice($tmp1,0,1);
					$c++;
				}
				$result=$tmp;
			}
		}
		$this->dbClose();

		return($result);
	}

	public function deletePage(){
		$lft=(int)$this->get("lft");
		$rgt=(int)$this->get("rgt");
		$num=$this->db->exec("UPDATE cms SET rgt=rgt-2 WHERE rgt>=$lft AND status=1;");
		$num=$this->db->exec("UPDATE cms SET lft=lft-2 WHERE lft>=$lft AND status=1;");
		return($this->delete());
	}
/*
	LOCATION VALUES:
		1=before
		2=after
		3=below (default)
		4=above
*/
	public function savePage($ar){
		$result=false;

		$relative_id=(int)$ar["relative_id"];
		$oldrelative_id=(int)$ar["oldrelative_id"];
		$location=(int)$ar["location"];
		$location=($location<1||$location>4)?3:$location;
		
		$lft=(int)$this->get("lft");
		$rgt=(int)$this->get("rgt");

		$isEdit=((int)$this->get("id")>0);
		print("<h1>is Edit: ".$this->get("id")."</h1>");
		if($isEdit){
			$this->delete();
		}

		$this->clear();

		unset($ar["relative_id"]);
		unset($ar["oldrelative_id"]);
		unset($ar["location"]);
		$ar["lft"]=$lft;
		$ar["rgt"]=$rgt;

		$this->create($ar);

		$doFinalSave=false;

		if($relative_id>0&&$relative_id!=$oldrelative_id){
			$this->dbConnect();

			//100% A-OK, UNLESS MOVING PARENT NODES!
			$relative=new cms();
			if($relative->getModelFromId($relative_id,"status=1")){
				$hasChildren=(((int)$ar["rgt"]-(int)$ar["lft"])>1)?true:false;
				if($hasChildren){
					$lft=(int)$this->get("lft");
					$rgt=(int)$this->get("rgt");
					$num=$this->db->exec("UPDATE cms SET rgt=rgt-1,lft=lft-1 WHERE lft BETWEEN $lft AND $rgt AND status=1;");
					$num=$this->db->exec("UPDATE cms SET rgt=rgt-2 WHERE rgt>=$rgt AND status=1;");
					$num=$this->db->exec("UPDATE cms SET lft=lft-2 WHERE lft>=$rgt AND status=1;");
				}else{
					if($isEdit){
						//Fix old left and rights (shuffle back) because we're effectively deleting an item out.
						//Check http://dev.mysql.com/tech-resources/articles/hierarchical-data.html as they have a better? approach.
						$lft=(int)$this->get("lft");
						$rgt=(int)$this->get("rgt");
						$num=$this->db->exec("UPDATE cms SET rgt=rgt-2 WHERE rgt>=$lft AND status=1;");
						$num=$this->db->exec("UPDATE cms SET lft=lft-2 WHERE lft>=$lft AND status=1;");
					}

					if($location==1){
						//1=Before (Previous Sibling)
						$lft=(int)$relative->get("lft");
						$rgt=$lft+1;
						$largerThan=$lft;
						print("<h1>lft $lft</h1>");
						print("<h1>rgt $rgt</h1>");
					}elseif($location==2){
						//2=After (Next Sibling) !!! WRONG
						$lft=(int)$relative->get("rgt")+1;
						$rgt=$lft+1;
						$largerThan=$lft;
					}elseif($location==3){
						//3=Below (Last Child)
						$lft=(int)$relative->get("lft")+1;
						$rgt=$lft+1;
						$largerThan=$lft;
					}
					$num=$this->db->exec("UPDATE cms SET rgt=rgt+2 WHERE rgt>=$largerThan AND status=1;");
					print("<h1>UPDATE cms SET rgt=rgt+2 WHERE rgt>=$largerThan AND status=1;</h1>");
					$doFinalSave=$this->db->exec("UPDATE cms SET lft=lft+2 WHERE lft>=$largerThan AND status=1;");
					print("<h1>UPDATE cms SET lft=lft+2 WHERE lft>=$largerThan AND status=1;</h1>");
				}
			}
			$this->dbClose();
			if($doFinalSave){
				$this->set("lft",$lft);
				$this->set("rgt",$rgt);
				$result=$this->save();
			}
		}else{
			$result=$this->save();
		}
		return($result);
	}

	public function loadPage(&$gravy){
		$result=false;
		if(is_array($gravy->rv["GRAVY_QS"])){
			if(count($gravy->rv["GRAVY_QS"])>0){
				if($this->getModelFromId(str_replace("_","-",$gravy->rv["GRAVY_QS"][0]),"status=1 AND published=1","url")){
					$tmp=$this->get("content");
					$content=array();
					if(preg_match_all("/^\[(.+)\]/im",$tmp,$matches)){
						$tmp=array();
						for($c=0;$c<count($matches[1]);$c++){
							$ar=preg_split("/\s*,\s*/",$matches[1][$c]);
							for($i=0;$i<count($ar);$i++){
								if(strpos($ar[$i],"=")){
									$tmp=split("=",$ar[$i]);
									$content[$tmp[0]]=$tmp[1];
								}else{
									$content[$ar[$i]]="";
								}
							}
						}
					}
					$content["cms"]=$this;
					$gravy->addTemplateData($content);

					$theme=$this->get("theme");
					$theme=(strlen($theme)<1)?$gravy->theme:$theme;
					$gravy->theme=$theme;

					$tmp=split(",",$this->get("controller"));

					$view=$tmp[0];
					$view=(strlen($view)<1)?$gravy->view:$view;

					$controller=$tmp[1];
					$controller=(strlen($controller)<1)?$gravy->controller:$controller;

					$gravy->setPageTitle($this->get("title"));
					$gravy->setPageTitle($this->get("title"));

					$gravy->redirectToView($view,$controller);
					$result=true;
				}
			}
		}
		return($result);
	}
}
?>